import { makeAutoObservable, observable } from 'mobx';
import * as api from './api';

export default class CompanyStore {
  _args = {
    search: {
    },
    pg: {
      page: 0,
      sort: ['crDate;desc'],
      size: 10,
    },
  };
  total = 0;
  company = {};
  loading = false;
  charges = [];
  surcharges = [];
  surchargesMap = {};
  defaultSurcharge = [];
  taurusSurcharges = [];


  constructor(rootStore) {
    this.rootStore = rootStore;
    makeAutoObservable(this, { rootStore: false });
  }

  * update(data) {
    yield api.update(data);
    this.get(data.id);
  }

  * get(id) {
    const res = yield api.getCompany(id);
    this.company = res;
    if (res?.surchargeSettlement && JSON.stringify(res?.surchargeSettlement) !== '{}') {
      const price = [];
      // eslint-disable-next-line guard-for-in
      for (const key in res?.surchargeSettlement) {
        price.push(res?.surchargeSettlement[key]);
      }
      this.charges = price;
    } else {
      this.charges = [];
    }
  }

  * getSurcharge() {
    const surcharge = yield api.getDict('taurusSurcharges');
    const initSelect = surcharge.map((item) => ({
      label: item.itemId,
      value: item.itemId,
    }));
    this.taurusSurcharges = surcharge;
    this.surcharges = initSelect;
    const enumerationSurcharges = surcharge.reduce((key, item) => {
      // eslint-disable-next-line no-param-reassign
      const { itemId, extras } = item;
      // eslint-disable-next-line no-param-reassign
      key[item.itemId] = {
        itemId,
        selectable: extras.selectable.value,
        disable: true,
      };
      return key;
    }, {});
    this.surchargesMap = enumerationSurcharges;
    return observable(this.initSelect);
  }

  * getRules() {
    const surcharge = yield api.getRules('surcharge', '默认附加费');
    this.defaultSurcharge = surcharge;
  }

  idx(i) {
    return this._args.pg.page * this._args.pg.size + i + 1;
  }

  get pg() {
    return this._args.pg;
  }

  set pg(pg) {
    this.query({ ...pg });
  }

  get search() {
    this._args.pg.page = 0;
    return this._args.search;
  }

  set search(search) {
    this._args.pg.page = 0;
    this._args.search = search;
  }

  get tableSort() {
    if (this._args.pg.sort?.length) {
      const [fn, dir] = this._args.pg.sort[0].split(';');
      return { [fn]: dir };
    }
    return undefined;
  }
}
